package com.wonders.frame.controller;

import com.gcr.server.response.Response;
import com.gcr.server.response.ResponseCodeEnum;
import com.wonders.frame.common.Enum.InitCommonSourceEnum;
import com.wonders.frame.common.Enum.SessionKeyEnum;
import com.wonders.frame.controller.core.CoreController;
import com.wonders.frame.entity.AuthAccount;
import com.wonders.frame.entity.AuthOrga;
import com.wonders.frame.entity.AuthRole;
import com.wonders.frame.entity.form.AuthOrgaForm;
import com.wonders.frame.repository.AuthOrgaRepository;
import com.wonders.frame.service.AuthOrgaService;
import com.wonders.frame.service.Core.CoreCurdService;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;


@RestController
@RequestMapping("/authOrga")
public class AuthOrgaController extends CoreController<AuthOrga> {
    Logger log = LoggerFactory.getLogger(AuthOrgaController.class);

    @Autowired
    private AuthOrgaService service;

    @Autowired
    private AuthOrgaRepository authOrgaRepository;

    @Override
    protected CoreCurdService getService() {
        return service;
    }

    private final ReentrantLock lock=new ReentrantLock();

    @RequestMapping("findAll")
    public List<AuthOrga> findAll(){
        log.info("request:authOrga/findAll");
        return service.findAll();
    }

    @RequestMapping("save")
    public Response save(@RequestBody AuthOrgaForm orgaForm){
        try {
            lock.lock();
            log.info("request:authOrga/save");
            log.info(orgaForm.toString());
            AuthOrga check =  service.checkUnique(orgaForm.getOrgaCode());
            if(Strings.isNotEmpty(orgaForm.getId())){
                //修改
                String codeNew = orgaForm.getOrgaCode();
                String codeOld = authOrgaRepository.findById(orgaForm.getId()).get().getOrgaCode();
                if(codeNew.equals(codeOld)){
                    AuthOrga authOrga = service.save(orgaForm);
                    InitCommonSourceEnum.INSTANCE.initOrga();
                    return successResponse(authOrga);
                }
            }
            //新增,或修改了code
            if(check != null){
                return errorResponse(-2,"机构代码重复",null);
            }else {
                AuthOrga authOrga = service.save(orgaForm);
                InitCommonSourceEnum.INSTANCE.initOrga();
                return successResponse(authOrga);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return errorResponse();
        }finally {
            lock.unlock();
        }
    }
    @RequestMapping("getOrgaTreeNode")
    public Response getOrgaTreeNode (){
        Response res = new Response();
        try {
            res.setContent(service.getOrgaNodeTree());
            res.setCode(ResponseCodeEnum.SUCCESS.getCode());
            res.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return errorResponse();
        }
    }

    /**
     * 机构管理员（新增用户）：获取本机构下的节点
     */
    @RequestMapping("getAccountOrgaTreeNode")
    public Response getAccountOrgaTreeNode(HttpServletRequest request){
        Response res = new Response();
        try {
            //获取用户session
            HttpSession session = request.getSession();
            AuthAccount authAccount = (AuthAccount) session.getAttribute(SessionKeyEnum.USERINFO.name());
            Boolean isAdmin = false;
            List<AuthRole> roles = new ArrayList<>( authAccount.getRoles());
            for(AuthRole role:roles){
                if(role.getRoleCode().equals("admin")){
                    isAdmin = true;
                    break;
                }
            }
            if(isAdmin){
                //超级管理员可以看所有
                res.setContent(service.getOrgaNodeTree());
                res.setCode(ResponseCodeEnum.SUCCESS.getCode());
                res.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
            }else{
/*                String orgaId = authAccount.getOrgaId();
                String deptId = authAccount.getDeptId();
                if(orgaId!=deptId){
                    orgaId=deptId;
                }
                List<AuthOrga> list = authOrgaRepository.findLikeOrgaTree(orgaId);*/
                AuthOrga ParentauthOrga  = authOrgaRepository.getOneAuthOrgaById(authAccount.getDeptId());
                List<AuthOrga> allOrgas=authOrgaRepository.findLikeOrgaTree(ParentauthOrga.getOrgaSerachindex());
                res.setContent(service.getAccountOrgaNodeTree(allOrgas));
                res.setCode(ResponseCodeEnum.SUCCESS.getCode());
                res.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
            }
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return errorResponse();
        }
    }

    @RequestMapping("getOneOrgaNode")
    public Response getNodeById(String id){
        try {
            AuthOrga authOrga = service.getNodeById(id);
            return successResponse(authOrga);
        } catch (Exception e) {
            e.printStackTrace();
            return errorResponse();
        }
    }
    @RequestMapping("deleteOrga")
    public Response deleteNodeById(String id){
        Response res = new Response();
        try {
            log.info("request:authOrga/deleteOrga");
            if(service.isExistAccount(id)){
                //存在用户不让删机构
                res.setCode(-2);
                res.setMsg("机构下面存在用户,不能删除");
                return res;
            }else{
                //可以删机构
                service.deleteById(id);
                res.setCode(ResponseCodeEnum.SUCCESS.getCode());
                res.setMsg(ResponseCodeEnum.SUCCESS.getMsg());
                InitCommonSourceEnum.INSTANCE.initOrga();
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return errorResponse();
        }
    }


    //获取飞防组织下面的权限树
    @GetMapping("/getOrgaTreeByOrgaCode")
    public Response getOrgaTreeByOrgaCode(String orgaCode){
        try {
            return successResponse(service.getOrgaTreeByOrgaCode(orgaCode));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //根据机构属性获取  机构
    @RequestMapping("/getOrgaTreeByOrgaProperty")
    public Response getOrgaTreeByOrgaProperty(String orgaProperty){
        try {
            return successResponse(service.getOrgaTreeByOrgaProperty(orgaProperty));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }


    @GetMapping("/getOrgaTreeNodeAndChecked")
    public Response getOrgaTreeNodeAndChecked(String orgaId){
        try {
            return successResponse( service.getOrgaTreeNodeAndChecked(orgaId));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

    //由机构id获取用户信息
    @RequestMapping("/getUsersByOrgaId")
    public Response getUsersByOrgaId(String orgaId){
        try {
            return successResponse( service.getAllUser(orgaId));
        }catch (Exception e){
            e.printStackTrace();
            return  errorResponse();
        }
    }

    //模糊查询机构节点
    @RequestMapping("/findNodeByOrgaName")
    public Response findNodeByOrgaName(Boolean flag,String orgaName,HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            AuthAccount acc =  (AuthAccount)session.getAttribute(SessionKeyEnum.USERINFO.name());
            return successResponse(service.findNodeByOrgaName(flag,orgaName,acc.getDeptId()));
        }catch (Exception e){
            e.printStackTrace();
            return errorResponse();
        }
    }

}
